import { DataContextFactory } from './../../domain/fbsDataContext';
import { Token } from './../../domain/model/token';
import { MD5 } from "../utils";
import { Identity } from './identity';
const webconfig = require("../../../webconfig").webconfig;

/**
 * 提供登录票据的发放，验证的单例对象
 * 
 * @export
 * @class TokenManager
 */
export class TokenManager {
    static Current: TokenManager = new TokenManager();
    private tokenList: Token[] = [];
    constructor() { }
    /**
     * @param  {string} userId
     * @param  {string} userName
     * @param  {string} tokenValue
     * @returns Token
     */
    AddToken(user: Identity, tokenValue: string): Token {
        let t = this.GetTokenByUserId(user.userId);
        if (!t) {
            let t = new Token(user, tokenValue);
            this.tokenList.push(t);
            this.SaveToDB(t);
        }
        return t;
    }
    /**
     * 根据用户名获取一个token 如果不存在返回 null
     * @param  {} userId 用户Id
     * @param  {} userName 登录用户名
     * @returns Token
     */
    GetTokenByUserId(userId: string): Token {
        let token = this.tokenList.find(x => x.Identity.userId == userId);
        return token;
    }
    GetTokenByAccount(account: string): Token {
        let token = this.tokenList.find(x => {
            return x.Identity.userName == account;
        });
        return token;
    }
    /**
     * 根据用户名获取一个token 如果不存在返回 null
     * @returns Token
     */
    GetTokenByToken(token: string): boolean {
        for (let item of this.tokenList) {
            if (item.TokenValue == token) {
                return true;
            }
        }
        return false;
    }

    RemoveTokenByUserId(userId: string) {
        let index = this.tokenList.findIndex(x => x.Identity.userId == userId);
        if (index) this.tokenList.splice(index, 1);
    }

    async SaveToDB(token: Token) {
        let ctx = DataContextFactory.GetDataContext();
        await ctx.Create(token);
    }
    async LoadFromDB() {
        let ctx = DataContextFactory.GetDataContext();
        let tList = await ctx.Token.ToList();
        this.tokenList = tList;
    }
    LoadFromConfig() {
        if (webconfig.authWhiteList) {
            for (let i = 0; i < webconfig.authWhiteList.length; i++) {
                let item = webconfig.authWhiteList[i];
                let tokenValue = MD5.hex_md5(item);
                let user: Identity = {
                    userId: "authWhiteList" + i,
                    userName: item,
                    password: ""
                };
                this.AddToken(user, tokenValue);
            }
        }
        console.log(this.tokenList.length, this.tokenList);
    }
}